package main

import (
	"fmt"
	"math/rand"
	"sort"
)

func main()  {
	//test1()
	test2()
}
//利用切片进行排序
func test1()  {
	var sliceInt = []int{1,-3,8,3,4,99}
	fmt.Println(sliceInt)
	sort.Ints(sliceInt)
	fmt.Println(sliceInt)
}
//对接口进行排序
func test2()  {
	var heroes HeroSlice
	for i:=0;i<10;i++ {
		hero := Hero{
			Name:fmt.Sprintf("hero-%d",rand.Intn(100)),
			Age:rand.Intn(100),
		}
		heroes = append(heroes,hero)
	}
	for _,v := range(heroes){
		fmt.Println(v)
	}
	sort.Sort(heroes)
	fmt.Println("==================")
	for _,v := range (heroes) {
		fmt.Println(v)
	}
}

type Hero struct {
	Name string
	Age int
}
//声明hero结构体的切片类型
type HeroSlice []Hero

func (hs HeroSlice)Len() int  {
	return len(hs)
}

func (hs HeroSlice)Less(i,j int)bool  {
	return hs[i].Age < hs[j].Age
}

func (hs HeroSlice)Swap(i,j int)  {
	temp := hs[i]
	hs[i] = hs[j]
	hs[j] = temp
}



